package handler

import (
	"boy-go/middlewares"
	"boy-go/modules/generator/service"
	"boy-go/modules/generator/vo"
	"boy-go/pkg/request"
	"boy-go/pkg/response"
	"boy-go/pkg/xnum"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

// AddGenTableRouter 添加路由
func AddGenTableRouter(group *gin.RouterGroup) {
	group.GET("/gen/:id", middlewares.HasPermission("tool:gen:query"), get_gen)
	group.GET("/gen/list", middlewares.HasPermission("tool:gen:list"), list_gen)
	group.GET("/gen/db/list", middlewares.HasPermission("tool:gen:list"), list_database)
	group.PUT("/gen/synchDb/:tableName", middlewares.HasPermission("tool:gen:edit"), middlewares.Logger("代码生成", middlewares.UPDATE), synchDb_gen)
	group.POST("/gen", middlewares.HasPermission("tool:gen:add"), middlewares.Logger("代码生成", middlewares.INSERT), add_gen)
	group.PUT("/gen", middlewares.HasPermission("tool:gen:edit"), middlewares.Logger("代码生成", middlewares.UPDATE), edit_gen)
	group.DELETE("/gen/:ids", middlewares.HasPermission("tool:gen:remove"), middlewares.Logger("代码生成", middlewares.DELETE), del_gen)
	group.POST("/gen/importTable", middlewares.HasPermission("tool:gen:import"), middlewares.Logger("代码生成", middlewares.IMPORT), importTable_gen)
	group.GET("/gen/preview/:tableId", middlewares.HasPermission("tool:gen:preview"), preview_gen)
	group.GET("/gen/batchGenCode", middlewares.HasPermission("tool:gen:code"), middlewares.Logger("代码生成", middlewares.GENCODE), batchGenCode)
}

// get_gen
// @Summary 获取代码生成业务表详情
// @Description 获取代码生成业务表详情（管理页面）
// @Tags system-gen
// @Accept json
// @Produce json
// @Param id path string true "ID"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/gen/{id} [get]
func get_gen(ctx *gin.Context) {
	var idStr = ctx.Param("id")
	id := xnum.Str2int64(idStr)
	m, err := service.NewGenTableService().GetById(id)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	tables := service.NewGenTableService().SelectGenTableAll()
	list := service.NewGenTableColumnService().SelectGenTableColumnListByTableId(id)
	rspMap := make(map[string]interface{})
	rspMap["info"] = m
	rspMap["tables"] = tables
	rspMap["rows"] = list
	response.AjaxSuccess(ctx, rspMap)
}

// list_gen
// @Summary 获取代码生成业务表列表
// @Description 获取代码生成业务表列表（管理页面）
// @Tags system-gen
// @Accept json
// @Produce json
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/gen/list [get]
func list_gen(ctx *gin.Context) {
	req := vo.QueryGenTableReq{}
	if err := ctx.BindQuery(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	req.Params = request.BindFormParams(ctx)
	page, err := service.NewGenTableService().List(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxDataTable(ctx, page.List, page.Total)
}

// add_gen
// @Summary 新增代码生成业务表
// @Description 新增代码生成业务表（管理页面）
// @Tags system-gen
// @Accept json
// @Produce json
// @Param req body  vo.AddGenTableReq true "req"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/gen [post]
func add_gen(ctx *gin.Context) {
	var req vo.AddGenTableReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	m, err := service.NewGenTableService().Add(&req)
	if err != nil {
		response.AjaxFailCode(ctx, response.ServerError)
	} else {
		response.AjaxSuccess(ctx, m)
	}
}

// edit_gen
// @Summary 编辑代码生成业务表
// @Description 编辑代码生成业务表（管理页面）
// @Tags system-gen
// @Accept json
// @Produce json
// @Param req body  vo.EditGenTableReq true "req"
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/gen [put]
func edit_gen(ctx *gin.Context) {
	var req vo.EditGenTableReq
	if err := ctx.ShouldBind(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err := service.NewGenTableService().ValidateEdit(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	m, err := service.NewGenTableService().Edit(&req)
	if err != nil {
		response.AjaxFailCode(ctx, response.ServerError)
	} else {
		response.AjaxSuccess(ctx, m)
	}
}

// del_gen
// @Summary 删除代码生成业务表
// @Description 删除代码生成业务表（管理页面）
// @Tags system-gen
// @Accept json
// @Produce json
// @Failure 400 {string} string "bad request"
// @Failure 500 {string} string "Internal Server Error"
// @Router /system/gen [delete]
func del_gen(ctx *gin.Context) {
	var idsStr = ctx.Param("ids")
	ids := strings.Split(idsStr, ",")
	err := service.NewGenTableService().BatchDel(ids)
	if err != nil {
		response.AjaxFailCode(ctx, response.ServerError)
	} else {
		response.AjaxSuccess(ctx, nil)
	}
}

func list_database(ctx *gin.Context) {
	req := vo.QueryGenTableReq{}
	if err := ctx.BindQuery(&req); err != nil {
		response.AjaxError(ctx, err)
		return
	}
	page, err := service.NewGenTableService().SelectDbTableList(&req)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxDataTable(ctx, page.List, page.Total)
}

func importTable_gen(ctx *gin.Context) {
	tableStr := ctx.Query("tables")
	if tableStr == "" {
		response.AjaxFail(ctx, response.ServerError, "参数错误")
		return
	}
	tables := strings.Split(tableStr, ",")
	tableList, err := service.NewGenTableService().SelectDbTableListByNames(tables)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	err = service.NewGenTableService().ImportGenTable(tableList, "admin")
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}

// synchDb 同步数据库
func synchDb_gen(ctx *gin.Context) {
	var tableName = ctx.Param("tableName")
	if tableName == "" {
		response.AjaxFail(ctx, response.ServerError, "参数错误[tableName不能为空]")
		return
	}
	err := service.NewGenTableService().SynchDb(tableName)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, nil)
}

func preview_gen(ctx *gin.Context) {
	var idsStr = ctx.Param("tableId")
	id := xnum.Str2int64(idsStr)
	m, err := service.NewGenTableService().PreviewCode(id)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	response.AjaxSuccess(ctx, m)
}

// batchGenCode 批量生产代码
func batchGenCode(ctx *gin.Context) {
	var idsStr = ctx.Query("tables")
	tableNames := strings.Split(idsStr, ",")
	buf, err := service.NewGenTableService().DownloadCode(tableNames)
	if err != nil {
		response.AjaxError(ctx, err)
		return
	}
	// 设置响应头，强制浏览器下载
	ctx.Header("Content-Type", "application/zip")
	ctx.Header("Content-Disposition", "attachment; filename=files_with_folders.zip")

	// 将 zip 数据作为响应体发送
	ctx.Data(http.StatusOK, "application/zip", buf)
}
